<template>
  <div class="myCompany">
    <el-tabs
      class="tab-container"
      v-model="activeName"
      type="border-card"
      @tab-click="handleClick"
    >
      <el-tab-pane label="公司信息" name="first">
        <el-form
          :model="companyInformationFormData"
          ref="companyInformationForm"
          label-position="top"
        >
          <el-form-item label="" prop="logo">
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleLogoSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="companyInformationFormData.logo"
                :src="companyInformationFormData.logo"
                style="max-width: 100px; max-height: 100px"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-row>
            <el-col :span="10">
              <el-form-item label="公司行业" prop="industryId">
                <el-cascader
                  v-model="companyInformationFormData.industryId"
                  :options="options"
                  :props="props"
                  @change="handleChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="10">
              <el-form-item label="公司全称" prop="name">
                <el-input
                  v-model="companyInformationFormData.name"
                  placeholder="公司全称"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="融资阶段" prop="financingStage">
                <el-select
                  v-model="companyInformationFormData.financingStage"
                  placeholder="请选择融资阶段"
                >
                  <el-option label="未融资" :value="1"></el-option>
                  <el-option label="天使轮" :value="2"></el-option>
                  <el-option label="A轮" :value="3"></el-option>
                  <el-option label="B轮" :value="4"></el-option>
                  <el-option label="C轮" :value="5"></el-option>
                  <el-option label="D轮及以上" :value="6"></el-option>
                  <el-option label="已上市" :value="7"></el-option>
                  <el-option label="不需要融资" :value="8"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="10">
              <el-form-item label="公司规模" prop="scala">
                <el-select
                  v-model="companyInformationFormData.scala"
                  placeholder="请选择公司规模"
                >
                  <el-option label="0~20人" :value="1"></el-option>
                  <el-option label="20~99人" :value="2"></el-option>
                  <el-option label="100~499人" :value="3"></el-option>
                  <el-option label="500~999人" :value="4"></el-option>
                  <el-option label="1000~9999人" :value="5"></el-option>
                  <el-option label="10000人以上" :value="6"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="其他自定义标签" prop="otherTag">
                <div class="flex gap-2">
                  <el-tag
                    v-for="tag in dynamicTags"
                    :key="tag"
                    closable
                    style="margin-left: 3px"
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-if="inputVisible"
                    ref="InputRef"
                    v-model="inputValue"
                    class="w-20"
                    size="small"
                    @keyup.enter="handleInputConfirm"
                    @blur="handleInputConfirm"
                  />
                  <el-button
                    style="margin-left: 3px"
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput"
                  >
                    + New Tag
                  </el-button>
                </div>
                <!-- <el-input
                  v-model="companyInformationFormData.otherTag"
                  placeholder="输入其他自定义标签"
                ></el-input> -->
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="10">
              <el-form-item label="公司地点" prop="location">
                <el-input
                  v-model="companyInformationFormData.location"
                  placeholder="公司地点"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="公司简介" prop="introduction">
            <v-md-editor
              v-model="companyInformationFormData.introduction"
              mode="edit"
            ></v-md-editor>
            <!-- <el-input v-model="companyInformationFormData.introduction" type="textarea" placeholder="公司简介"></el-input> -->
          </el-form-item>
          <el-form-item>
            <el-button
              style="margin-left: 480px"
              type="primary"
              @click="submitCompanyForm"
            >
              提交更新
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="工商信息表" name="second">
        <el-form
          :model="businessFormData"
          ref="businessForm"
          label-position="top"
        >
          <el-row>
            <el-col :span="10">
              <el-form-item label="经营状态" prop="status">
                <el-select
                  v-model="businessFormData.status"
                  placeholder="请选择经营状态"
                >
                  <el-option label="存续" :value="1"></el-option>
                  <el-option label="在业" :value="2"></el-option>
                  <el-option label="吊销" :value="3"></el-option>
                  <el-option label="注销" :value="4"></el-option>
                  <el-option label="迁入" :value="5"></el-option>
                  <el-option label="迁出" :value="6"></el-option>
                  <el-option label="停业" :value="7"></el-option>
                  <el-option label="清算" :value="8"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="10">
              <el-form-item label="公司全称" prop="name">
                <el-input
                  v-model="businessFormData.name"
                  placeholder="公司全称"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="成立时间" prop="establishmentTime">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="businessFormData.establishmentTime"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="10">
              <el-form-item label="注册资金" prop="registeredCapital">
                <el-input-number
                  :min="0"
                  v-model="businessFormData.registeredCapital"
                  placeholder="注册资金"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="法人代表" prop="legalRepresentative">
                <el-input
                  v-model="businessFormData.legalRepresentative"
                  placeholder="法人代表"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="10">
              <el-form-item label="注册地址" prop="registeredLocation">
                <el-input
                  v-model="businessFormData.registeredLocation"
                  placeholder="注册地址"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="统一信用代码" prop="code">
                <el-input
                  v-model="businessFormData.code"
                  placeholder="统一信用代码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="10">
              <el-form-item label="所属行业" prop="industry">
                <el-input
                  v-model="businessFormData.industry"
                  placeholder="所属行业"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="所在地" prop="location">
                <el-input
                  v-model="businessFormData.location"
                  placeholder="所在地"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="10">
              <el-form-item label="登记机关" prop="registrationAuthority">
                <el-input
                  v-model="businessFormData.registrationAuthority"
                  placeholder="登记机关"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="10">
              <el-form-item label="营业期限" prop="businessTerm">
                <el-input
                  v-model="businessFormData.businessTerm"
                  placeholder="营业期限"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2"></el-col>
            <el-col :span="10">
              <el-form-item label="企业类型" prop="type">
                <el-input
                  v-model="businessFormData.type"
                  placeholder="企业类型"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="经营范围" prop="scope">
            <el-input
              v-model="businessFormData.scope"
              type="textarea"
              placeholder="经营范围"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              style="margin-left: 480px"
              @click="submitBusinessForm"
            >
              提交更新
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick } from 'vue'
import {
  getCompanyInfoById,
  getHrOneById,
  getHrMe,
  putCompanyOne,
  putCompanyBusiness,
} from '@/servers/controller'
import { useUserStoreHook } from '@/store/modules/user'
import { ElMessage, ElInput } from 'element-plus'

onMounted(() => {
  loadData()
})

const userStore = useUserStoreHook()
const activeName = ref('first')

let companyInformationForm = ref()
const companyInformationFormData = ref({
  logo: '',
  id: null,
  cid: null,
  name: '',
  introduction: '',
  financingStage: 1,
  scala: 1,
  industryName: '',
  industryId: 0,
  otherTag: [],
  location: '',
})

let businessForm = ref()
const businessFormData = ref({
  id: null,
  companyId: null,
  name: '',
  establishmentTime: '',
  registeredCapital: 10000,
  legalRepresentative: '',
  registeredLocation: '',
  code: '',
  industry: '',
  location: '',
  registrationAuthority: '',
  businessTerm: '',
  type: '',
  status: 2,
  scope: '',
})

const handleClick = () => {
  console.log('tab click')
}

//tags//////////////////////////////////

const inputValue = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

const handleClose = (tag: string) => {
  //@ts-ignore
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    //@ts-ignore
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}
///////////////////////////////////////////

//获取标签//////////////////////////////
const options = ref([])
const value = ref([])

const props = {
  expandTrigger: 'hover' as const,
  value: 'id',
  label: 'name',
  checkStrictly: true, //只显示最后一个
}

const getAllTag = async () => {
  let storageTag = sessionStorage.getItem('allTag')
  if (storageTag != null) {
    options.value = JSON.parse(storageTag)
    console.log('options:', options.value)
    return
  }
  try {
    //@ts-ignore
    const { data } = await getAllTag()
    sessionStorage.setItem('allTag', JSON.stringify(data.data))
    options.value = data.data
  } catch (e) {
    ElMessage.error((e as Error).message)
  }
  console.log('options:', options.value)
}

const handleChange = (value: any) => {
  console.log(value)
}
//////////////////////////////////////////

const submitBusinessForm = async () => {
  // @ts-ignore
  const res = await putCompanyBusiness(businessFormData.value)
  if (res.data.code === 200) {
    ElMessage.success('更新成功')
  } else {
    ElMessage.error('更新失败')
  }
}

const submitCompanyForm = async () => {
  let industryNumber = companyInformationFormData.value.industryId
  if (
    Array.isArray(companyInformationFormData.value.industryId) &&
    companyInformationFormData.value.industryId.length > 0
  ) {
    // @ts-ignore
    const industryList: [] = companyInformationFormData.value.industryId
    industryNumber = industryList[industryList.length - 1]
    console.log('industryId:', industryNumber)
  }
  const updateCompanyForm = {
    name: companyInformationFormData.value.name,
    introduction: companyInformationFormData.value.introduction,
    financingStage: companyInformationFormData.value.financingStage,
    scala: companyInformationFormData.value.scala,
    industry: industryNumber,
    otherTag: dynamicTags.value,
    location: companyInformationFormData.value.location,
    logo: companyInformationFormData.value.logo,
    cid: companyInformationFormData.value.cid,
  }
  console.log('updateCompanyForm:', updateCompanyForm)
  // @ts-ignore
  const res = await putCompanyOne(updateCompanyForm)
  if (res.data.code === 200) {
    ElMessage.success('更新成功')
  } else {
    ElMessage.error('更新失败')
  }
}
/////////////////////////////////////////////////
interface Node {
  id: number
  name: string
  sort: number
  level: number
  parentId: number
  status: number
  createTime: string
  children: Node[]
}

function findIdByName(name: string): number | null {
  // @ts-ignore
  const stack = [...options] // 使用堆栈进行迭代
  while (stack.length) {
    const item = stack.pop()
    if (item?.name === name) {
      return item.id
    }
    stack.push(...(item?.children || []))
  }
  return null
}
///////////////////////////////////////////////////
const loadData = async () => {
  await getAllTag()
  if (userStore.userInfo.id !== undefined) {
    // const res = await getHrOneById({
    //   id: userStore.userInfo.id,
    // })

    const res = await getHrMe()

    if (res.data.code === 200) {
      //获取公司信息
      // @ts-ignore
      companyInformationFormData.value = { ...res.data.data.companyInfoVo }
      dynamicTags.value = companyInformationFormData.value.otherTag
      const companyId = res.data.data.companyInfoVo.id
      // @ts-ignore
      companyInformationFormData.value.cid = companyId
      console.log('companyInfor:', companyInformationFormData.value)
      //获取工商信息
      const res1 = await getCompanyInfoById({ id: companyId })
      if (res1.data.code === 200) {
        // @ts-ignore
        businessFormData.value = { ...res1.data.data.businessInformationVo }
        // @ts-ignore
        businessFormData.value.companyId = companyId
      } else {
        ElMessage.error('获取失败:' + res1.data.message)
      }
    } else {
      ElMessage.error('获取失败:' + res.data.message)
    }
  }
}

const handleLogoSuccess = (res: any, file: any) => {
  companyInformationFormData.value.logo = URL.createObjectURL(file.raw)
}

const beforeAvatarUpload = (file: any) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}
</script>

<style scoped lang="scss">
.myCompany {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  overflow: auto;
  max-height: 700px; /* 设置最大高度，超出时将显示滚动条 */
}

.tab-container {
  min-width: 600px;
  min-height: 300px;
}
</style>
